package com.springcloud.redis.jhs.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.springcloud.redis.jhs.constants.Constants;
import com.springcloud.redis.jhs.entities.Product;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author liyanhao
 * @Date 2022-11-24 21:57
 */
@RestController
@Slf4j
@Api(description = "聚划算商品列表接口")
public class JHSProductController {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询 在高并发的情况下，只能走redis查询 走db的必定会把db打垮
     */
    @RequestMapping(value = "/product/find", method = RequestMethod.GET)
    @ApiOperation("按照分页和每页显示容量,点击查看")
    public List<Product> find(int page, int size) {
        List<Product> list = null;
        int start = (page - 1) * size;
        int end = start + size - 1;
        try {
            //采用redis list数据结构的lrang命令实现分页查询
            list = this.redisTemplate.opsForList().range(Constants.JHS_KEY, start, end);
            if (CollectionUtil.isEmpty(list)) {
                //
            }
            log.info("查询结果:{}", list);

        } catch (Exception exception) {
            //这里异常 一般是redis瘫痪 或者redis网络timeout
            log.error("exception:" + exception);
            //todo 走DB查询
        }
        return list;
    }
}
